import React from 'react'
import './add-topic.css'
import {connect,} from 'react-redux'
import {withRouter,} from 'react-router-dom'
import FormInput from "../../shared-components/FormInput/FormInput";
import CustomButton from "../../shared-components/CustomButton/CustomBotton";
import GoBackLayout from "../../layouts/GoBackLayout/GoBackLayout";
import constants from "../../utils/constants";
import {Icon, ImagePicker, Modal, NavBar, TextareaItem, } from "antd-mobile";
import UnChecked from '../../res/images/web/topic/choose agree@2x.png'
import Checked from '../../res/images/web/topic/choose agree-selected@2x.png'
import LocalStorageService from "../../utils/LocalStorageService";
import UploadImage from "../../utils/image";
import {goBack} from "../../utils/goback";



class AddTopic extends React.Component {

    constructor(props) {
        super(props)
        this.uid = LocalStorageService.get('userid')
        this.state = {
            title: '',
            txt: '',
            files: [],
            fm: null,
            lock: false,
            modalVisible: false,
        }
    }

    onChange = (e, type) => {
        const v = e.target.value
        this.setState({
            [type]: v,
        })
    }

    onImgPick = (files, type, index) => {
        this.setState({
            files: files,
        })
    }

    unLock = () => {
        this.setState({
            lock: !this.state.lock,
        })
    }


    submit = () => {
        const txt = this.state.txt
        const title = this.state.title
        const files = this.state.files
        const uid = this.uid
        const clock = this.state.lock ? 1 : 0
        const login = LocalStorageService.get('isLogin')
        if (login) {
            const fm = new FormData()
            let imgs = []
            fm.append('uid', uid)
            fm.append('title', title)
            fm.append('txt', txt)
            fm.append('clock', clock)
            // setTimeout(() => {
            //     for (let i = 0; i < files.length; i++) {
            //         let file = files[i]
            //         let name = file.file.name
            //         let imgIns = new UploadImage(file.file)
            //         let params = {
            //             file: file.file,
            //             targetSize: 100 * 1024,
            //             quality: 1,
            //             width: 800,
            //             fileName: name,
            //             callback: (r) => {
            //                 imgs.push(name)
            //                 fm.append(name, r)
            //             }
            //         }
            //         imgIns.zipImage(params)
            //     }
            // }, 0)
            // setTieout(() => {
            //     fm.append('imgs', JSON.stringify(imgs))
            //     const endCallback = () => {
            //         this.props.history.goBack()
            //     }
            //     this.props.doAddTopic({fm: fm, endCallback: endCallback,})
            // }, 0)

            let promiseList = files.map(async (file) => {
                let name = file.file.name
                let imgIns = new UploadImage(file.file)
                let params = {
                    file: file.file,
                    targetSize: 1000 * 1024,
                    quality: 1,
                    width: 800,
                    fileName: name,
                }
                let p = await imgIns.zipImage(params)
                return p
            })
            Promise.all(promiseList).then((files) => {
                files.map(file => {
                    fm.append([file.name], file,)
                    imgs.push(file.name)
                })

                fm.append('imgs', JSON.stringify(imgs))

                const endCallback = () => {
                    this.props.history.goBack()
                }

                this.props.doAddTopic({fm: fm, endCallback: endCallback,})
            })
        }

    }

    left = (history) => {
        // title: '',
        // txt: '',
        // files: [],
        // fm: null,
        // lock: false,
        const title = this.state.title
        const txt = this.state.txt
        const files = this.state.files
        const isEdit = title !== '' || txt !== '' || files.length > 0
        if (isEdit) {
            this.setState({
                modalVisible: true,
            })
            // const btnList = [
            //     { text: <span>取消</span>, onPress: () => {}},
            //     { text: <span>确认</span>, onPress: () => goBack(history) },
            // ]
            // Modal.alert('确认退出', '', btnList)
        } else {
            goBack(history)
        }


    }

    render() {
        const history = this.props.history
        const title = this.state.title
        const txt = this.state.txt
        const files = this.state.files
        const lock = this.state.lock
        const modalVisible = this.state.modalVisible

        const modal = <div>
            <Modal
                visible={modalVisible}
                transparent
                onClose={() => {
                    this.setState({
                        modalVisible: false,
                    })
                }}
            >
                <p style={{
                    lineHeight: '40px',
                }}>确认退出</p>
                <div className='flex-space-between-align-center'>
                    <p
                        style={{width: '50%', lineHeight: '40px',}}
                        onClick={() => this.setState({modalVisible: false,})}
                    >取消</p>
                    <p
                        style={{color: '#FFA500', width: '50%', lineHeight: '40px',}}
                        onClick={() => goBack(history)}
                    >确认</p>
                </div>
            </Modal>
        </div>

        const rightContent = <div
            style={{
                height: 24,
                width: 64,
                borderRadius: '4px',
                backgroundColor: constants.themeColor,
                textAlign: 'center',
            }}
            onClick={this.submit}
        >
            <span
                style={{
                    color: '#fff',
                    lineHeight: '24px',
                    fontSize: '12px',
                    // fontSize:
                }}
            >发送</span>
        </div>

        const banned = <div
            style={{
                textAlign: 'center',
                height: '24px',
                width: '100%',
            }}
        >
            <span
                style={{
                    lineHeight: '24px',
                    fontSize: '12px',
                    opacity: '0.4',
                }}
            >请遵守法律规范，违规者封号处理</span>
        </div>

        const form = <div
            style={{
                background: '#fff',
                padding: '8px',
            }}
        >
            <FormInput
                placeholder='标题...'
                value={title}
                onChange={e => this.onChange(e, 'title')}
            />
            <textarea
                value={txt}
                onChange={e => this.onChange(e, 'txt')}
                className='add-topic-textarea'
                style={{
                    padding: '0.5rem',
                    boxSizing: 'border-box',
                    width: '100%',
                    height: '200px',
                }}
                placeholder='这一刻的想法...'
            />

            <ImagePicker
                files={files}
                multiple
                selectable={files.length < 9}
                onChange={this.onImgPick}
            />
        </div>

        const bottom = <div style={{
            width: '100%',
            height: '50px',
            marginTop: '1px',
            background: '#fff',
            padding: '16px',
            boxSizing: 'border-box',
        }} className='flex-align-center'>
            <img
                src={!lock ? Checked : UnChecked}
                alt=''
                style={{
                    height: 12, width: 12, marginRight: '8px',
                }}
                onClick={this.unLock}
            />
            <span>锁定帖子（别人不能回复）</span>
        </div>
        // <NavBar
        //     mode="light"
        //     icon={left}
        //     onLeftClick={() => goBack(history, toIndex,)}
        //     rightContent={rightContent}
        //     extra={title}
        //         >
        //         {mainTitle ? mainTitle : ''}
        // </NavBar>
        const left = (
            <div className='flex-space-between-align-center'>
                <Icon type="left" size='lg' style={{color: `#333`}}/>
                <span className='go-back-layout-icon-title'>发帖</span>
            </div>
        )
        const bar = <NavBar
            mode='light'
            icon={left}
            onLeftClick={() => this.left(history,)}
            rightContent={rightContent}
        >
        </NavBar>

        return <>
            {modalVisible ? modal : ''}
            {bar}
            {banned}
            {form}
            {bottom}
        </>

        return <GoBackLayout
            title='发帖'
            history={history}
            rightContent={rightContent}
        >
            {banned}
            {form}
            {bottom}
        </GoBackLayout>
    }

}

const mapState = (state) => ({
    user: state.user,
    topic: state.topic,
})

const mapDispatch = (dispatch) => ({
    doAddTopic: (payload) => dispatch.topic.doAddTopic(payload),
    fetchUserDetail: (payload) => dispatch.user.fetchUserDetail(payload)
})

export default connect(mapState, mapDispatch)(withRouter(AddTopic))
